<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区-->
    <el-card class="box-card">
      <!--搜索和添加区-->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!--用户列表区-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!--修改按钮-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              size="mini"
            />
            <!--删除按钮-->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            />
            <!--角色分配按钮-->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!--内容主体-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户的对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!--内容主体-->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色的对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <!--内容主体-->
      <p>当前的用户：{{ userInfo.username }}</p>
      <p>当前的角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRoleInfo(userInfo.id, selectedRoleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  userInfoRequest,
  putUserStatue,
  addUserRequest,
  queryUserById,
  changeUserInfo,
  removeUserById,
  setRole,
} from "../../network/users";
import { rolesListRequest } from "../../network/power";
import { checkEmail, checkMobile } from "./checkForm";

export default {
  name: "Users",
  created() {
    this.getUsersList();
  },
  data() {
    return {
      // 查询用户的参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 用户列表
      userList: [],
      // 用户总数
      total: 0,
      // 控制添加在用户对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单的验证对象
      addFormRules: {
        username: [
          //验证为必填项
          { required: true, message: "请输入用户名", trigger: "blur" },
          //验证长度
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        //验证密码
        password: [
          //验证为必填项
          { required: true, message: "请输入密码", trigger: "blur" },
          //验证长度
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号码不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
      // 控制修改在用户对话框的显示和隐藏
      editDialogVisible: false,
      // 查询用户信息
      editForm: {},
      // 修改用户的表单验证
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号码不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
      // 控制分配角色对话框的显示和隐藏
      setRoleDialogVisible: false,
      // 用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 已选择的id值
      selectedRoleId: "",
    };
  },
  methods: {
    // 获取用户列表
    getUsersList() {
      userInfoRequest(this.queryInfo)
        .then((res) => {
          // console.log(res)
          this.userList = res.data["users"];
          this.total = res.data.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 监听每页显示的数据个数改变事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize;
      this.getUsersList();
    },
    // 监听页码改变
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    // 监听状态改变
    userStatusChange(userInfo) {
      // console.log(userInfo)
      putUserStatue(userInfo)
        .then((res) => {
          // console.log(res)
          this.$message.success(res["meta"].msg);
        })
        .catch((err) => {
          userInfo.mg_state = !userInfo.mg_state;
          console.log(err);
          this.$message.error("更改用户状态失败");
        });
    },
    // 对话框关闭的回调函数
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加预校验
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        // 预校验成功发送请求
        addUserRequest(this.addForm)
          .then((res) => {
            // console.log(res)
            this.$message.success(res["meta"].msg);
            // 隐藏对话框
            this.addDialogVisible = false;
            // 更新列表
            this.getUsersList();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.log(err);
          });
      });
    },
    // 点击修改的回调
    showEditDialog(id) {
      queryUserById(id)
        .then((res) => {
          // console.log(res)
          this.editForm = res.data;
          this.editDialogVisible = true;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("查询失败");
        });
    },
    // 修改对话框关闭的回调函数
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改的预校验
    changeUserInfo() {
      this.$refs.editFormRef.validate((valid) => {
        // console.log(valid)
        if (!valid) return;
        changeUserInfo(this.editForm)
          .then((res) => {
            this.$message.success(res["meta"].msg);
            this.editDialogVisible = false;
            this.getUsersList();
          })
          .catch((err) => {
            this.$message.error("修改失败");
            console.log(err);
          });
      });
    },
    // 删除数据
    removeUserById(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeUserById(id)
            .then((res) => {
              this.getUsersList();
              this.$message.success(res["meta"].msg);
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 分配角色
    setRole(userInfo) {
      this.userInfo = userInfo;
      rolesListRequest()
        .then((res) => {
          this.rolesList = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
      this.setRoleDialogVisible = true;
    },
    // 分配角色对话框确定的回调
    saveRoleInfo(id, rid) {
      if (!rid) {
        return this.$message.error('请选择分配的角色')
      }
      setRole(id, rid)
        .then((res) => {
          this.getUsersList();
          this.$message.success(res.meta.msg);
          this.setRoleDialogVisible = false;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("设置角色失败");
        });
    },
    // 分配角色对话框关闭的回调
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = []
    }
  },
};
</script>

<style scoped>
</style>